﻿using System;
using System.Data;
using System.Web.UI.WebControls;

namespace _513X0018_web08
{
    public partial class AspDataAccessing : System.Web.UI.Page
    {
        DataSet ds;
        bool blnSet = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            ds = CreateDataSet();
            blnSet = true;
            if (Page.IsPostBack == false)
                BindGrid();
        }
        void BindGrid()
        {
            dgColors.DataSource = ds;
            dgColors.DataMember = "Colors";
            DataBind();
        }
        DataSet CreateDataSet()
        {
            int i;
            string[] arrColors;
            if (ViewState["Colors"] == null)
            {
                arrColors = new string[7] { "red", "orange", "yellow", "green", "blue", "indigo", "violet" };
                ViewState["Colors"] = arrColors;
            }
            else
                arrColors = (string[])ViewState["Colors"];
            DataSet ds = new DataSet("MyDataSet");
            DataTable dTable = new DataTable("Colors");
            dTable.Columns.Add("Color",
            Type.GetType("System.String"));
            dTable.Columns.Add("ID",
            Type.GetType("System.Int32"));
            ds.Tables.Add(dTable);
            for (i = 0; i <= 6; i++)
            {
                DataRow dr = dTable.NewRow(); dr[0] = arrColors[i].ToString(); dr[1] = i; dTable.Rows.Add(dr);
            }
            return ds;
        }

        protected void ChangeColor(object sender, DataGridItemEventArgs e)
        {
            int intIndex = e.Item.ItemIndex;
            string str;
            if (blnSet)
            {
                if (intIndex > -1)
                {
                    str = (string)ds.Tables["Colors"].Rows[intIndex]["Color"];
                    e.Item.BackColor = System.Drawing.Color.FromName(str);
                }
            }
        }
        protected void dgColors_Edit(object Sender, DataGridCommandEventArgs e)
        {
            dgColors.EditItemIndex = e.Item.ItemIndex;
            BindGrid();
        }
        protected void dgColors_Cancel(object Sender, DataGridCommandEventArgs e)
        {
            dgColors.EditItemIndex = -1;
            BindGrid();
        }
        protected void dgColors_Update(object Sender, DataGridCommandEventArgs e)
        {
            TextBox tb = (TextBox)e.Item.Cells[1].Controls[0];
            String strColor = tb.Text;
            ds.Tables["Colors"].Rows[e.Item.ItemIndex]["Color"] =
            strColor;
            ((string[])ViewState["Colors"])[e.Item.ItemIndex] = strColor;
            dgColors.EditItemIndex = -1;
            BindGrid();
        }
    }
}